package com.ykdl.member.kid.circle;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;
import oauth.signpost.http.HttpParameters;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.BitmapUtils;
import com.ykdl.member.kid.R;
import com.ykdl.member.constant.KidAction;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.beans.GroupsBean;
import com.ykdl.member.kid.beans.Listinfobean;
import com.ykdl.member.kid.beans.ResetPasswordBean;
import com.ykdl.member.kid.gears.BaseScreen;
import com.ykdl.member.kid.gears.HomeActivity;
import com.ykdl.member.kid.image.ImageLoader;
import com.ykdl.member.kid.image.ImageOptionsFactory;
import com.ykdl.member.kid.prefs.CircleStatePrefs;
import com.ykdl.member.kid.widget.AsyncImageView;
import com.ykdl.member.kid.widget.RefreshListView;
import com.ykdl.member.views.IaskMenuBarView;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

public class AllCircleActivity extends BaseScreen{
	private ArrayList<Listinfobean>  groupbeanlist;
	private String TAG = this.getClass().getSimpleName();
	private RefreshListView allcicle_list = null;
	private AllCircleAdapter adapter ;
	private boolean isJoinOk = true ;
	private  CircleStatePrefs circleState;
	private int start_id = 0;
	private int cursor = 0;
	private int count = 20;
	private IaskMenuBarView iask_menu_bar ;
	private boolean isexite = true ;
	private BitmapUtils bitmapUtil ;
	private boolean isloaddate=false;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTopTitle("全部圈子", 0, R.drawable.back_bg, new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!isexite) {
					go(HomeActivity.class);
					finish();
				}else {
					if (isloaddate) {
						setResult(RESULT_OK);
					}
					finish();
				}
			}
		}, 0, 0, null, R.drawable.title_bg, false);
		setContent(R.layout.allcircleactivity_xml);
		bitmapUtil = new BitmapUtils(this);
		bitmapUtil.configDefaultLoadingImage(R.drawable.circle_default);
		bitmapUtil.configDefaultLoadFailedImage(R.drawable.circle_default);
		if (this.getIntent().getStringExtra(KidAction.FROM)!=null) {
			isexite = false ;
		}else {
			isexite = true ;
		}
		iask_menu_bar = (IaskMenuBarView)findViewById(R.id.iask_menu_bar);
		iask_menu_bar.setSelectedID(R.id.bar_mycircle);
		iask_menu_bar.setBaseScreen(this);
		if (isexite) {
			iask_menu_bar.setVisibility(View.GONE);
			mLeft.setVisibility(View.VISIBLE);
		}else {
			mLeft.setVisibility(View.INVISIBLE);
			iask_menu_bar.setVisibility(View.VISIBLE);
		}
		circleState = new CircleStatePrefs(mContext);
		circleState.clearData();
		allcicle_list = (RefreshListView) findViewById(R.id.allcicle_list);
		adapter = new AllCircleAdapter();
		 allcicle_list.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
						long arg3) {
					// TODO Auto-generated method stub
					
						Listinfobean bean = (Listinfobean)adapter.getItem(arg2);
						goGroup(bean,true);
					
				}
			}) ;
			 allcicle_list.setMoreClick(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					inint();
				}
			});
		inint();
	}
	
	private void inint() {
		showProgress("正在加载中,请稍等...");
		String  pageurl = KidConfig.GET_ALL_GROUPS;
		Map<String, String> map = new HashMap<String, String>();
		map.put("start_id", String.valueOf(start_id));
		map.put("cursor", String.valueOf(cursor));
		map.put("count", String.valueOf(count));
		HttpBaseRequest request  =  Wxxr.getInstance().getRequest(pageurl, map,null);
		 TaskManager.startHttpRequest(request, new getgroupTag(),  GroupsBean.class);
		
		
	}
	class getgroupTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			if (t instanceof GroupsBean) {
				finishProgress();
				GroupsBean bean = (GroupsBean)t;
				if (bean.getNext_cursor() == bean.getTotal_number()) {
					allcicle_list.setMoreButtoIsGon(true);
				} else {
					allcicle_list.setMoreButtoIsGon(false);
					cursor = bean.getNext_cursor();
				}
					groupbeanlist = bean.getList();
					adapter.setList(groupbeanlist);
					adapter.notifyDataSetChanged();
					allcicle_list.setAdapter(adapter);
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "加载失败", 1).show();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			
		}
		
	}
	class AllCircleAdapter extends BaseAdapter {
		ArrayList<Listinfobean>   list;

		public void setList(ArrayList<Listinfobean> list) {
			this.list = list;
		}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			if (list!=null) {
				return list.size();
			}else {
				return 0;
			}
			
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			if (getCount() != 0) {
				return list.get(arg0-1);
			} else {
				return null;
			}
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = RelativeLayout.inflate(mContext,
						R.layout.allcircle_item, null);
				holder = new ViewHolder();
				holder.head = (AsyncImageView) convertView.findViewById(R.id.head);
				holder.notice = (TextView) convertView.findViewById(R.id.notice);
				holder.membernum = (TextView) convertView.findViewById(R.id.member_num);
				holder.contentnum = (TextView) convertView.findViewById(R.id.content_num);
				holder.groupname = (TextView) convertView.findViewById(R.id.group_name);
				holder.isinput_but = (Button) convertView.findViewById(R.id.isinput_but);
				convertView.setTag(holder);
			}else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.groupname.setText(list.get(position).getGroup_name());
			holder.membernum.setText(list.get(position).getMember_count()+"");
			holder.contentnum.setText(list.get(position).getTopic_count()+"");
			holder.notice.setText(list.get(position).getDescription());
			if (list.get(position).getIcon_file_meta()!=null) {
				String url = list.get(position).getIcon_file_meta().getDownload_urls().getOrigin().getUrl();
				bitmapUtil.display(holder.head, url);
			}else {
				holder.head.setDefaultDrawable(	getResources().getDrawable(R.drawable.circle_default));
			}
			final Listinfobean bean =list.get(position);
			holder.head.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent  = new Intent(mContext, CircleInfoActivity.class);
					
					intent.putExtra("group_id", bean.getGroup_id()+"");
					startActivity(intent);
				}
			});
			final int intposition = position ;
			if (list.get(position).isIs_member()&&isJoinOk) {
				circleState.setCircleState(list.get(intposition).getGroup_id()+"", "true");
				holder.isinput_but.setBackgroundResource(R.drawable.isinput_but_true_bg);
			}else {
				holder.isinput_but.setBackgroundResource(R.drawable.isinput_but_false_bg);
			}
//			holder.isinput_but.setSelected(list.get(position).isIs_member());
			
				holder.isinput_but.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if(islogon()){
							if (list.get(intposition).isIs_member()) {
								deltGroup(list.get(intposition).getGroup_id()+"");
							}else {
								joinGroup(list.get(intposition).getGroup_id()+"");
							}
						}
					}
				});
			if ("true".equals(circleState.getCircleState(list.get(intposition)
					.getGroup_id() + ""))) {
				holder.isinput_but.setBackgroundResource(R.drawable.isinput_but_true_bg);
			} else {
				holder.isinput_but.setBackgroundResource(R.drawable.isinput_but_false_bg);
			}
			return convertView;
		}
		
	}
	class ViewHolder {
		AsyncImageView head;
		TextView notice;
		TextView membernum;
		TextView contentnum;
		TextView groupname;
		Button isinput_but;
		
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		ImageLoader.getInstance().setCurrentActivity(TAG);
		super.onResume();
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		ImageLoader.getInstance().pause(TAG);
		super.onPause();
	}
	public void joinGroup(String group_id ) {
		showProgress("正在发送请稍等...");
		String  pageurl = KidConfig.GET_GROUP_MEMBER;
		HttpParameters bodyParams = new HttpParameters();
		HttpBaseRequest request  =  Wxxr.getInstance().postBaseRequest(pageurl+group_id,bodyParams, null);
		 TaskManager.startHttpRequest(request, new joingroupTag(group_id,request),  ResetPasswordBean.class);
	}
	private class joingroupTag implements ITag {
		private String id ;
		HttpBaseRequest request ;
		public joingroupTag(String group_id,HttpBaseRequest request){
			id = group_id ;
			this.request = request ;
		}
		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			finishProgress();
			if (t instanceof ResetPasswordBean) {
				ResetPasswordBean bean = (ResetPasswordBean)t;
				if (bean.getStatus()==0) {
					isJoinOk=false;
					isloaddate = true ;
					circleState.setCircleState(id, "true");
					Toast.makeText(mContext, "加入成功", 1).show();
					adapter.notifyDataSetChanged();
				}
				
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "加入失败", 1).show();
			return true;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			request.cancel();
		}
		
	}
	public void deltGroup(String group_id ) {
		showProgress("正在发送请稍等...");
		String  pageurl = KidConfig.GET_GROUP_MEMBER;
		HttpParameters bodyParams = new HttpParameters();
//		bodyParams.put("", value)
		HttpBaseRequest request  =  Wxxr.getInstance().deltteRequest(pageurl+group_id,bodyParams);
		 TaskManager.startHttpRequest(request, new deltgroupTag(group_id,request),  ResetPasswordBean.class);
	}
	private class deltgroupTag implements ITag {
		private String id ;
		HttpBaseRequest request ;
		public deltgroupTag(String group_id,HttpBaseRequest request){
			id = group_id ;
			this.request = request ;
		}
		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			finishProgress();
			if (t instanceof ResetPasswordBean) {
				ResetPasswordBean bean = (ResetPasswordBean)t;
				if (bean.getStatus()==0) {
					circleState.setCircleState(id, "false");
					isJoinOk=false;
					isloaddate = true ;
					Toast.makeText(mContext, "退出成功", 1).show();
					adapter.notifyDataSetChanged();
				}
				
			}
			
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			Toast.makeText(mContext, "退出失败", 1).show();
			finishProgress();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			request.cancel();
		}
		
	}
	public void goGroup(Listinfobean bean,boolean where) {
		Intent intent =null ;
		if (where) {
			intent  = new Intent(mContext, CircleTopicActivity.class);
		}else {
			intent  = new Intent(mContext, CircleInfoActivity.class);
		}
		intent.putExtra("bean", bean);
		intent.putExtra("group_id", bean.getGroup_id()+"");
		startActivity(intent);
	}
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		if (!isexite) {
			go(HomeActivity.class);
			finish();
		}else {
			if (isloaddate) {
				setResult(RESULT_OK);
			}
			finish();
		}
		
	}
}
